package com.weijian.iotdb;

import org.apache.iotdb.isession.SessionDataSet;
import org.apache.iotdb.isession.util.Version;
import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.apache.iotdb.session.Session;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args)
            throws IoTDBConnectionException, StatementExecutionException {

        System.out.println("Hello IoTDB Java Example");

        // 初始化与连接
        Session session = new Session.Builder()
                .host("47.122.63.169")
                .port(6667)
                .username("root")
                .password("root")
                .version(Version.V_1_0)
                .build();
        // 开启Session RPC不压缩
        session.open(false);

        // 插入数据
        List<Object> values = new ArrayList<>();
        values.add(88);
        insertRecord(session, values);

        // 查询数据
        queryRecord(session);

        // 关闭连接
        session.close();
    }

    private static void insertRecord(Session session, List<Object> values) throws IoTDBConnectionException, StatementExecutionException {
        List<String> measurements = new ArrayList<>();
        List<TSDataType> types = new ArrayList<>();
        measurements.add("status");
        types.add(TSDataType.INT32);
        session.insertRecord("root.test.test", System.currentTimeMillis(), measurements, types, values);
        System.out.println("————————————————写入数据成功————————————————");
    }

    private static void queryRecord(Session session) throws IoTDBConnectionException, StatementExecutionException {
        System.out.println("————————————————查询数据开始————————————————");
        try (SessionDataSet dataSet = session.executeQueryStatement("select status from root.test.test")) {
            System.out.println(dataSet.getColumnNames());
            dataSet.setFetchSize(1024); // default is 10000
            while (dataSet.hasNext()) {
                System.out.println(dataSet.next());
            }
        }
        System.out.println("————————————————查询数据结束————————————————");
    }
}
